<?php
namespace app\admin\controller;
use think\swoole\facade\Task;
use app\common\lib\Redis;
use app\common\lib\GatewayCurl;

class Device extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function deviceList() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        $role = $this->role;
        
        $params = request()->get();
        $page = isset($params['page']) ? intval($params['page']) : 1;
        $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 20;
        $offset = ($page - 1) * $pageSize;
        
        $time = time();
        $where = [];
        
        if(isset($params['online']) && $params['online'] !== ''){
            $online = $params['online'];
            if($online == 0){  //掉线
                $where[] = ['heart_time', '<=', $time - 300];
            }else{
                $where[] = ['heart_time', '>', $time - 300];
            }
        }
        
        $gateway = !empty($params['gateway']) ? intval($params['gateway']) : 0;
        if($gateway > 0) {
            $where[] = ['gateway', '=', $gateway];
        }
        
        if(isset($params['allot']) && $params['allot'] !== ''){
            $allot = intval($params['allot']);
            if($allot == 0){  //未分配
                if($this->role == 1) {
                    $where[] = ['agent_id', '=', 0];
                }elseif($this->role == 2) {
                    $where[] = ['store_id', '=', 0];
                }
            }else { //已分配
                if($this->role == 1) {
                    $where[] = ['agent_id', '<>', 0];
                }elseif($this->role == 2) {
                    $where[] = ['store_id', '<>', 0];
                }
            }
        }
        
        $deviceNo = isset($params['deviceNo']) ? trim($params['deviceNo']) : '';
        if($deviceNo !== '') {
            $where[] = ['device_no', 'like', '%' . $deviceNo . '%'];
        }
        
        $deviceName = isset($params['deviceName']) ? trim($params['deviceName']) : '';
        if($deviceName !== '') {
            $where[] = ['device_name', 'like', '%' . $deviceName . '%'];
        }
        
        $simIccId = isset($params['simIccId']) ? trim($params['simIccId']) : '';
        if($simIccId !== '') {
            $where[] = ['sim_iccid', 'like', '%' . $simIccId . '%'];
        }
        
        $field = ['device_id', 'device_no', 'device_name', 'sim_iccid', 'port_number', 'address', 'price_id', 'heart_time', 'signal', 'lock_status', 'coin_amount', 'card_amount', 'online_card_amount', 'online_amount'];
        
        $deviceModel = model('Device');
        
        if($role == 1) { //平台的
            array_push($field, 'agent_id', 'store_id', 'gateway');
            $deviceList = $deviceModel->where($where)->field($field)->order('device_id desc')->limit($offset, $pageSize)->select()->toArray();
            if(!empty($deviceList)){
                $agentIds = [];
                $storeIds = [];
                foreach ($deviceList as $device) {
                    if($device['agent_id'] > 0) {
                        if(!in_array($device['agent_id'], $agentIds)){
                            array_push($agentIds, $device['agent_id']);
                        }
                        
                        if($device['store_id'] > 0 && !in_array($device['store_id'], $storeIds)) {
                            array_push($storeIds, $device['store_id']);
                        }
                    }
                }
                
                $agentList = [];
                $storeList = [];
                
                if(!empty($agentIds)) {
                    $agentList = model('Agent')->findAll(['agent_id' => $agentIds], ['agent_id', 'agent_name']);
                    
                    if(!empty($storeIds)){
                        $storeList = model('Store')->findAll(['store_id' => $storeIds], ['store_id', 'store_name']);
                    }
                    
                    foreach ($deviceList as &$device) {
                        if($device['agent_id'] > 0) {
                            foreach ($agentList as $agent) {
                                if($device['agent_id'] == $agent['agent_id']) {
                                    $device['agent_name'] = $agent['agent_name'];
                                    break;
                                }
                            }
                            if($device['store_id'] > 0) {
                                foreach ($storeList as $store) {
                                    if($device['store_id'] == $store['store_id']) {
                                        $device['store_name'] = $store['store_name'];
                                        break;
                                    }
                                }
                            }
                        }
                        
                        
                    }
                }
                
                
                
            }
            
            
        }elseif ($role == 2){ //代理商
            array_push($field, 'store_id');
            $deviceList = $deviceModel->where($where)->field($field)->order('device_id desc')->limit($offset, $pageSize)->select()->toArray();
            if(!empty($deviceList)){
                $storeIds = [];
                foreach ($deviceList as $device) {
                    if($device['store_id'] > 0 && !in_array($device['store_id'], $storeIds)){
                        array_push($storeIds, $device['store_id']);
                    }
                }
                
                if(!empty($storeIds)) {
                    $storeList = model('Store')->findAll(['store_id' => $storeIds], ['store_id', 'store_name']);
                    foreach ($deviceList as &$device) {
                        if($device['store_id'] > 0) {
                            foreach ($storeList as $store) {
                                if($device['store_id'] == $store['store_id']) {
                                    $device['store_name'] = $store['store_name'];
                                    break;
                                }
                            }
                        }
                        
                    }
                }
                
            }
        }else{ //门店
            $deviceList = $deviceModel->where($where)->field($field)->order('device_id desc')->limit($offset, $pageSize)->select()->toArray();
        }
        
        $priceIds = [];
        foreach ($deviceList as &$device) {
            if($device['heart_time'] > ($time - 300)) {
                $device['online'] = 1;
            }else{
                $device['signal'] = 0;
                $device['online'] = 0;
            }
            
            if($device['price_id'] > 0 && !in_array($device['price_id'], $priceIds)) {
                array_push($priceIds, $device['price_id']);
            }
        }

        if(!empty($priceIds)) {
            $priceList = model('ChargePrice')->findAll(['price_id' => $priceIds], ['price_id', 'role', 'owner_id', 'charge_type', 'price_name', 'options', 'class_rate', 'prepayment']);
            foreach ($deviceList as &$device) {
                if($device['price_id'] > 0) {
                    foreach ($priceList as $price) {
                        if($device['price_id'] == $price['price_id']) {
                            $device['charge_price'] = $price;
                            if($this->role == $price['role'] && $this->userid == $price['owner_id']){
                                $device['charge_price']['owner'] = true;
                            }else{
                                $device['charge_price']['owner'] = false;
                            }
                            
                            unset($device['charge_price']['owner_id']);
                            unset($device['charge_price']['role']);
                            
                        }
                    }
                    
                }
            }
        }
        
        $repData = ['list' => $deviceList];
        
        if(isset($params['init']) && $params['init'] == 1){
            $repData['total'] = $deviceModel->where($where)->count();
        }
        
        return successResult($repData);
    }
    
    public function deviceType() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        $type = request()->get('type', 0, 'intval');
        $config = config('device_type.device_type');
        if($type > 0){
            $config = $config[$type]['charge_mode'];
            $data = [];
            foreach ($config as $k => $item) {
                array_push($data, ['value' => $k, 'name' => $item]);
            }
            
        }else{
            $data = [];
            foreach ($config as $k => $item) {
                array_push($data, ['value' => $k, 'name' => $item['name']]);
            }
        }
        
        return successResult(['list' => $data]);
    }
    
    private function updateDeviceLngLatByAddress(&$deviceModel, $deviceId) {
        $key = config('config.amap.geocode');
        Task::async(function() use(&$deviceModel, $deviceId, $key) {
            try {
                $device = $deviceModel->findOne(['device_id' => $deviceId], ['province', 'city', 'district', 'address', 'device_type']);
                $address = '';
                if(!empty($device['city'])) {
                    $address .= $device['city'];
                }
                if(!empty($device['district'])) {
                    $address .= $device['district'];
                }
                if(!empty($device['address'])) {
                    $address .= $device['address'];
                }
                
                if($address === '') {
                    return true;
                }
                
                $url = 'https://restapi.amap.com/v3/geocode/geo?output=JSON&address=' . $address . '&key=' . $key;

                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                $body = curl_exec($curl);
                curl_close($curl);
                if(!empty($body)) {
                    $body = json_decode($body, true);
                    if(empty($body)) return;

                    if(isset($body['status']) && $body['status'] == 1) {
                        $location = $body['geocodes'][0]['location'];
                        if(!empty($location)) {
                            $result = explode(',', $location);
                            $lng = isset($result[0]) ? floatval($result[0]) : null;
                            $lat = isset($result[1]) ? floatval($result[1]) : null;
                            if($lng && $lat) {
                                $deviceModel->modify(['device_id' => $deviceId], ['longitude' => $lng, 'latitude' => $lat]);
                                unset($deviceModel);
                                $redis = new Redis();
                                $redis->geoadd('near_device_' . $device['device_type'], $lng, $lat, $deviceId);
                                $redis->close();
                            }
                            
                            
                        }
                    }
                }
            } catch (\Exception $e) {

            }
            
            return true;
        });
        
        return true;
    }
    
    public function save() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        if($this->role != 1 && $this->role != 2) {
            return errorResult();
        }
        
        $params = request()->post();
        
        $data['device_type'] = isset($params['device_type']) ? intval($params['device_type']) : 0;
        if($data['device_type'] <= 0){
            return errorResult('请选择设备类型');
        }
        
        $data['charge_mode'] = isset($params['charge_mode']) ? intval($params['charge_mode']) : 0;
        if($data['charge_mode'] <= 0){
            return errorResult('请选择设备类型');
        }
        
        $data['sim_iccid'] = isset($params['sim_iccid']) ? trim($params['sim_iccid']) : '';
        if($data['sim_iccid'] === ''){
            return errorResult('请填写sim iccid');
        }
        
        $data['port_number'] = isset($params['port_number']) ? intval($params['port_number']) : 0;
        if($data['port_number'] <= 0){
            return errorResult('请填写端口数');
        }
        
        $data['gateway'] = isset($params['gateway']) ? intval($params['gateway']) : 0;   //所属网关
        if($data['gateway'] <= 0) {
            return errorResult('请选择网关');
        }
        $data['agent_id'] = isset($params['agent_id']) ? intval($params['agent_id']) : 0; //代理商
        $data['coin_limit'] = isset($params['coin_limit']) ? intval($params['coin_limit']) : 0; //投币警告
        $data['price_id'] = isset($params['price_id']) ? intval($params['price_id']) : 0; //价格iD
        $data['network_type'] = isset($params['network_type']) ? intval($params['network_type']) : 0; //网络类型
        $data['sim_fee'] = isset($params['sim_fee']) ? floatval($params['sim_fee']) : 0; //流量费
        
        $simExpire = isset($params['sim_expire']) ? trim($params['sim_expire']) : ''; //下次缴费时间
        if($simExpire !== '') {
            $data['sim_expire'] = strtotime($simExpire);
        }
        
        $data['device_name'] = isset($params['device_name']) ? trim($params['device_name']) : ''; //设备名称
        //$data['longitude'] = isset($params['longitude']) ? floatval($params['longitude']) : 0; //经度
        //$data['latitude'] = isset($params['latitude']) ? floatval($params['latitude']) : 0; //纬度
        
        $data['province_id'] = isset($params['province_id']) ? intval($params['province_id']) : 0; //
        $data['city_id'] = isset($params['city_id']) ? intval($params['city_id']) : 0; //
        $data['district_id'] = isset($params['district_id']) ? intval($params['district_id']) : 0; //
        $data['address'] = isset($params['address']) ? trim($params['address']) : ''; //
        
        $data['remarks'] = isset($params['remarks']) ? trim($params['remarks']) : ''; //备注
        $data['status'] = isset($params['status']) ? intval($params['status']) : 0; //0:不启用，1：启用
        
        
        if($data['province_id'] > 0){
            $areaModel = model('Area');
            $data['province'] = $areaModel->where(['id' => $data['province_id']])->value('name');
            if($data['city_id'] > 0){
                $data['city'] = $areaModel->where(['id' => $data['city_id']])->value('name');
                if($data['district_id'] > 0){
                    $data['district'] = $areaModel->where(['id' => $data['district_id']])->value('name');
                }
            }
        }
        
        $deviceId = isset($params['device_id']) ? intval($params['device_id']) : 0; //设备id
        
        if($deviceId < 0){
            return errorResult();
        }
        
        $deviceModel = model('Device');
        $time = time();
        
        if($deviceId > 0) { //编辑
            $fields = array_keys($data);
            $device = $deviceModel->findOne(['device_id' => $deviceId], $fields);
            if(empty($device)){
                return errorResult();
            }
            
            $updateData = [];
            foreach ($data as $k => $val) {
                if($device[$k] != $val) { //有修改
                    $updateData[$k] = $val;
                }
            }
            
            if(empty($updateData)) {
                return successResult('修改成功');
            }
            
            if(isset($updateData['device_no'])) {
                $rs = $deviceModel->findOne(['device_no' => $updateData['device_no']], ['device_id']);
                if(!empty($rs)) {
                    return errorResult('已存在相同的设备号');
                }
            }
            
            if(isset($updateData['sim_iccid'])) {
                $rs = $deviceModel->findOne(['sim_iccid' => $updateData['sim_iccid']], ['device_id']);
                if(!empty($rs)) {
                    return errorResult('已存在相同的sim iccid');
                }
            }
            
            if(isset($updateData['agent_id'])) { //换代理商
                $updateData['store_id'] = 0;
            }
            
            $deviceModel->startTrans();
            
            try {
                $rs = $deviceModel->modify(['device_id' => $deviceId], $updateData);
                if($rs === false) {
                    $deviceModel->rollback();
                    return errorResult('修改失败1');
                }
                
                if(isset($updateData['port_number'])){
                    $portModel = model('DevicePort');
                    $offset = $updateData['port_number'] - $device['port_number'];
                    if($offset > 0){ //增加端口
                        $portData = [];
                        for($i = 1; $i <= $offset; $i ++){
                            array_push($portData, ['device_id' => $deviceId, 'port_no' => $device['port_number'] + $i]);
                        }
                        
                        $rs = $portModel->addAll($portData);
                        if(!$rs) {
                            $deviceModel->rollback();
                            return errorResult('修改失败2');
                        }
                    }else{ //减少端口
                        $offset = abs($offset);
                        $portNos = [];
                        
                        for($i = 0; $i < $offset; $i ++){
                            array_push($portNos, $device['port_number'] - $i);
                        }
                        
                        $rs = $portModel->where([['device_id', '=', $deviceId], ['port_no', 'in', $portNos]])->delete();
                        if(!$rs) {
                            $deviceModel->rollback();
                            return errorResult('修改失败3');
                        }
                    }
                }
                
                if(isset($updateData['sim_iccid'])) {
                    $curl = new GatewayCurl($data['gateway']);
                    $curl->send('updateLocalDeviceId', ['deviceId' => $updateData['sim_iccid'], 'id' => $deviceId]);
                }

                $deviceModel->commit();
                
                $this->updateDeviceLngLatByAddress($deviceModel, $deviceId);
                
                return successResult('修改成功');
                
            } catch (\Exception $e) {
                $deviceModel->rollback();
                return errorResult($e->getMessage());
            }
            
        }else{ //新增
            //查询是否存在一样的simiccid
            $device = $deviceModel->findOne(['sim_iccid' => $data['sim_iccid']], ['device_id']);
            if(!empty($device)) {
                return errorResult('已存在相同的sim iccid');
            }
            
            $deviceModel->startTrans();
            
            try {
                model('DeviceAddLock')->where(['id' => 1])->lock(true)->find();
                
                $toDay = strtotime(date('Y-m-d', $time));
                //计算几天添加的设备数量
                $count = $deviceModel->where([['create_time', '>=', $toDay]])->count() + 1;
                $data['device_no'] = date('ymd') . str_pad(strval($count), 5, '0', STR_PAD_LEFT);
                $data['create_time'] = $time;
                
                $deviceId = $deviceModel->add($data);
                if(!$deviceId){
                    $deviceModel->rollback();
                    return errorResult('添加设备失败');
                }
                
                $portData = [];
                for($i = 1; $i <= $data['port_number']; $i ++){
                    array_push($portData, ['device_id' => $deviceId, 'port_no' => $i]);
                }
                
                $rs = model('DevicePort')->addAll($portData);
                if(!$rs){
                    $deviceModel->rollback();
                    return errorResult('添加设备失败');
                }
                
                $curl = new GatewayCurl($data['gateway']);
                $curl->send('updateLocalDeviceId', ['deviceId' => $data['sim_iccid'], 'id' => $deviceId]);
                
                $deviceModel->commit();
                
                $this->updateDeviceLngLatByAddress($deviceModel, $deviceId);
                
                return successResult('新增设备成功');
                
            } catch (\Exception $e) {
                $deviceModel->rollback();
                return errorResult($e->getMessage());
            }
            
        }
    }
    
    public function getEditInfo() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        if($this->role != 1 && $this->role != 2) {
            return errorResult();
        }
        
        $deviceId = request()->get('id', 0, 'intval');
        if($deviceId <= 0) {
            return errorResult();
        }
        
        $field = ['device_type', 'charge_mode', 'port_number', 'sim_iccid', 'agent_id', 'coin_limit', 'price_id', 'gateway', 'network_type', 'sim_fee', 'sim_expire', 'device_name', 'province_id', 'city_id', 'district_id', 'address', 'longitude', 'latitude', 'remarks'];
        
        $device = model('Device')->findOne(['device_id' => $deviceId], $field);
        
        if($this->role == 2) {
            if($device['agent_id'] != $this->userid){
                return errorResult();
            }
        }

        return successResult($device);
        
    }
    
    //设置价格
    public function setPrice() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }

        if($this->role != 1 && $this->role != 2){
            return errorResult('无权限设置价格');
        }
        $params = request()->post();
        $priceId = isset($params['priceId']) ? intval($params['priceId']) : 0;
        if($priceId <= 0) {
            return errorResult('请选择价格');
        }
        
        $deviceIds = isset($params['deviceIds']) ? $params['deviceIds'] : [];
        if(empty($deviceIds) || !is_array($deviceIds)){
            return errorResult();
        }
        
        $price = model('ChargePrice')->findOne(['price_id' => $priceId], ['role', 'owner_id']);
        if(empty($price) || $this->role != $price['role'] || $this->userid != $price['owner_id']) {
            return errorResult();
        }
        
        
        
        $where = ['device_id' => $deviceIds];
        if($this->role == 2) {
            $where['agent_id'] = $this->userid;
        }
        
        $rs = model('Device')->modify($where, ['price_id' => $priceId]);
        if($rs === false){
            return errorResult('设置价格失败');
        }
        
        return successResult('设置价格成功');
        
    }
    
    //分配代理商
    public function allotAgent() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        if($this->role != 1) {
            return errorResult();
        }
        
        $params = request()->post();
        $agentId = isset($params['agentId']) ? intval($params['agentId']) : 0;
        if($agentId <= 0){
            return errorResult();
        }
        
        $deviceIds = isset($params['deviceIds']) ? $params['deviceIds'] : [];
        if(empty($deviceIds) || !is_array($deviceIds)) {
            return errorResult();
        }
        
        foreach ($deviceIds as &$deviceId) {
            $deviceId = intval($deviceId);
        }
        
        $rs = model('Device')->modify([['device_id', 'in', $deviceIds], ['agent_id', '<>', $agentId]], ['store_id' => 0, 'agent_id' => $agentId]);
        if($rs === false){
            return errorResult('分配设备失败');
        }

        return successResult('分配设备成功');
        
    }
    
    //分配门店
    public function allotStore() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        if($this->role != 2) {
            return errorResult();
        }
        
        $params = request()->post();
        $storeId = isset($params['storeId']) ? intval($params['storeId']) : 0;
        if($storeId <= 0){
            return errorResult();
        }
        
        $deviceIds = isset($params['deviceIds']) ? $params['deviceIds'] : [];
        if(empty($deviceIds) || !is_array($deviceIds)) {
            return errorResult();
        }
        
        foreach ($deviceIds as &$deviceId) {
            $deviceId = intval($deviceId);
        }
        
        $rs = model('Device')->modify(['device_id' => $deviceIds], ['store_id' => $storeId]);
        if($rs === false){
            return errorResult('分配设备失败');
        }
        
        return successResult('分配设备成功');
        
    }
    
    //下发设备运行参数
    public function sendChargeRule() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        if($this->role != 1 && $this->role != 2) {
            return errorResult();
        }
        
        $params = request()->post();
        $deviceIds = isset($params['deviceIds']) ? $params['deviceIds'] : [];
        if(!is_array($deviceIds) || empty($deviceIds)) {
            return errorResult('请选择设备');
        }

        try {
            $deviceModel = model('Device');
            $priceModel = model('ChargePrice');
            $prices = [];
            
            foreach ($deviceIds as $deviceId) {
                $device = $deviceModel->findOne(['device_id' => intval($deviceId)], ['price_id', 'sim_iccid', 'gateway']);
                if(empty($device) || $device['price_id'] <= 0 || empty($device['sim_iccid'])) {
                    continue;
                }
                
                $price = isset($prices[$device['price_id']]) ? $prices[$device['price_id']] : null;
                if(empty($price)) {
                    $price = $priceModel->findOne(['price_id' => $device['price_id']]);
                    $prices[$device['price_id']] = $price;
                }
                
                $classRate = $price['class_rate'];
                if(empty($classRate)) {
                    continue;
                }
                
                if(!is_array($classRate)) {
                    $classRate = json_decode($classRate, true);
                }
                
                $params = [
                    'deviceId' => $device['sim_iccid'],
                    'maxPower' => $price['max_power'],
                    'fullPower' => $price['critical_power'],
                    'fullTime' => $price['check_time'],
                    'minCalcUint' => $price['charge_type'] == 1 ? $price['charge_unit'] : $price['charge_unit'] * 100,
                    'mode' => $price['charge_type'],
                    'chargeUnit' => $price['prepayment'] * 1
                ];
                
                foreach ($classRate as $k => $rate) {
                    if($price['charge_type'] == 2) { //计量的
                        $rate['q'] *= 100;
                    }
                    
                    $params['powerLevel' . ($k + 1)] = $rate['w'];
                    $params['timeLevel' . ($k + 1)] = $rate['q'];
                }
                
                Task::async(function() use($device, $params) {
                    $params['deviceId'] = $device['sim_iccid'];
                    $curl = new GatewayCurl($device['gateway']);
                    $rs = $curl->send('setChargePriceRule', $params);

                });
                    
            }
            
            
            
        } catch (\Exception $e) {
            return errorResult($e->getMessage());
        }
        
        return successResult("发送成功");
        
    }
    
    
    public function getDetail() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        if($this->role != 1 && $this->role != 2) {
            return errorResult();
        }
        
        $deviceId = request()->get('deviceId', 0, 'intval');
        if($deviceId <= 0) {
            return errorResult();
        }
        
        $device = model('Device')->findOne(['device_id' => $deviceId]);
        if($this->role == 2) {
            if($device['agent_id'] != $this->userid) {
                return errorResult();
            }
        }elseif($this->role == 3) {
            if($device['store_id'] != $this->userid) {
                return errorResult();
            }
        }
        
        if($device['agent_id'] > 0) {
            $device['agent_name'] = model('Agent')->where(['agent_id' => $device['agent_id']])->value('agent_name');
            if($device['store_id'] > 0) {
                $device['store_name'] = model('Store')->where(['store_id' => $device['store_id']])->value('store_name');
            }
        }
        
        $device['port'] = model('DevicePort')->findAll(['device_id' => $deviceId], ['port_no', 'port_id', 'status', 'surplus_time', 'surplus_energy', 'power']);
        
        return successResult($device);
    }
    
    //删除设备
    public function delete() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }
        
        if($this->role != 1) {
            return errorResult('无权限删除设备');
        }

        $deviceId = request()->post('deviceId', 0, 'intval');
        if($deviceId <= 0) {
            return errorResult();
        }
        
        $model = model('Device');
        
        $model->startTrans();
        $redis = new Redis();
        
        try {
            
            $device = $model->where(['device_id' => $deviceId])->field(['device_type'])->lock(true)->find();
            if(empty($device)) {
                $model->rollback();
                $redis->close();
                return errorResult('删除设备失败');
            }
            
            $rs = $model->where(['device_id' => $deviceId])->delete();
            if(!$rs) {
                $model->rollback();
                $redis->close();
                return errorResult('删除设备失败');
            }
            
            $rs = model('DevicePort')->where(['device_id' => $deviceId])->delete();
            if(!$rs) {
                $model->rollback();
                $redis->close();
                return errorResult('删除设备失败');
            }
            
            $redis->handler()->zRem('near_device_' . $device['device_type'], $deviceId);
            
            $model->commit();
            $redis->close();
            
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult($e->getMessage());
        }
        
        return successResult('删除设备成功');
        
    }
    
    //切换锁
    public function updateDeviceLock() {
        $params = request()->post();
        $deviceId = isset($params['deviceId']) ? intval($params['deviceId']) : 0;
        if($deviceId <= 0) {
            return errorResult();
        }
        
        $status = isset($params['status']) ? intval($params['status']) : 0;
        
        $device = model('Device')->findOne(['device_id' => $deviceId], ['sim_iccid', 'gateway']);
        if(empty($device)) {
            return errorResult();
        }
  
        $curl = new GatewayCurl($device['gateway']);
        $rs = $curl->send('setChargePriceRule', ['deviceId' => $device['sim_iccid'], 'lockStatus' => $status]);

        if($rs['success'] == true) {
            return successResult('发送成功');
        }else{
            return errorResult('发送失败');
        }
    }
}







